package com.kmzx.gen.signs.tasks;

import com.kmzx.gen.signs.api.FileApi;
import com.kmzx.gen.signs.config.GateProfileConfig;
import com.kmzx.gen.signs.dto.BackToRecord;
import com.kmzx.gen.signs.dto.ENT312Message;
import com.kmzx.gen.signs.dto.OrderReturn;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project gen_sign
 * @Author: carol
 * @Date: 2020/7/22-15:03
 */

@Component
public class SeaUpCronTask {

    private static Logger logger = LoggerFactory.getLogger(SeaUpCronTask.class);

    @Autowired
    private FileApi fileApi;

    @Autowired
    GateProfileConfig gateProfileConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void scanBackFiles() {
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        Object fileState = forValue.get("--FileState--");
        String state = (String) fileState;
        if ("run".equals(state)) {
            forValue.set("--FileState--", "stop");
            logger.info("海关回执文件,扫描>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            String path = gateProfileConfig.getReceiptPath();
            Map<String, String> map = new HashMap<>();
            try {
                File topFile = new File(path);
                File[] allFiles = topFile.listFiles();
                int length = allFiles.length;
                logger.info("海关回执文件,扫描>>到:{}个文件", length);

                if (allFiles != null && length > 0) {
                    ArrayList<BackToRecord> toRecords = new ArrayList<>();
                    List<File> files = Arrays.asList(allFiles);
                    files = files.stream().sorted((f1, f2) -> {
                        long diff = f2.lastModified() - f1.lastModified();
                        if (diff > 0)
                            return -1;//倒序正序控制
                        else if (diff == 0)
                            return 0;
                        else
                            return 1;//倒序正序控制
                    }).collect(Collectors.toList());
                    XStream xstream = new XStream(new DomDriver("utf-8"));
                    xstream.addPermission(AnyTypePermission.ANY);
                    xstream.processAnnotations(ENT312Message.class);

                    // 记录文件
                    ArrayList<File> moveList = new ArrayList<>();
                    for (int i = 0; i < files.size(); i++) {
                        File file = files.get(i);
                        String name = file.getName();
                        long backStamp = file.lastModified();
                        logger.info("扫描海关回执文件,第[ {} ]个文件:名称:{}", i + 1, name);
                        if (name.startsWith("CEB312Message") && name.endsWith(".xml")) {
                            ENT312Message result = (ENT312Message) xstream.fromXML(file);
                            OrderReturn aReturn = result.getOrderReturn();

                            String returnStatus = aReturn.getReturnStatus();


                            BackToRecord back = new BackToRecord();
                            back.setContent("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + result.toXML()).setFileName(name)
                                    .setGuid(result.getGuid()).setLastModified(backStamp)
                                    .setSeaId(result.getGuid().substring(0, result.guid.length() - 4));
                            back.setOrderCode(aReturn.getOrderNo());

                            // 操作结果（2电子口岸申报中/3发送海 关成功/4发送海关失败/100海关退单 /120海关入库）,若小于0数字表示处理 异常回执
                            back.setReason(aReturn.getReturnInfo());
                            if (returnStatus.equals("2")) {
                                back.setSuccess(2);
                            } else if (returnStatus.equals("3")) {
                                back.setSuccess(3);
                            } else if (returnStatus.equals("4")) {
                                back.setSuccess(4);
                            } else if (returnStatus.equals("100")) {
                                back.setSuccess(100);
                            } else if (returnStatus.equals("120")) {
                                back.setSuccess(120);
                            }


                            moveList.add(file);
                            toRecords.add(back);
                        }
                        logger.info("moveList 文件数为:{}", moveList.size());
                    }

                    for (BackToRecord back : toRecords) {
                        String seaId = back.getSeaId();
                        map.put(seaId, back.getContent());
                    }

                    // 首先更新数据库
                    fileApi.updatePushDataFile(toRecords);

                    // 再更新推送
//                    fileApi.pushBackFile(map);
//                    fileApi.pushBackFile2(toRecords);

                    // 再异动文件夹
                    fileApi.moveOkFiles(moveList);
                    forValue.set("--FileState--", "run");
                } else {
                    forValue.set("--FileState--", "run");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


//                ObjectInputStream objectInputStream = xstream.createObjectInputStream(new FileInputStream(files[i]));
//                // 记录
//                for (ENT312Message message : messages) {
//                    String guid = message.getGuid();
//                    String key = guid.substring(0, guid.length() - 4);
//                    map.put(key, message.toXML());
//                }
//            Arrays.sort(files, new CompratorByLastModified());
